package xin.marcher.module.construction.repository;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Repository;
import xin.marcher.module.common.core.PageResult;
import xin.marcher.module.common.exception.CommonErrorCodeEnum;
import xin.marcher.module.common.exception.ProductBizException;
import xin.marcher.module.construction.converter.ProductConverter;
import xin.marcher.module.construction.domain.dto.ProducingAreaDTO;
import xin.marcher.module.construction.domain.entity.ProducingAreaDO;
import xin.marcher.module.construction.domain.request.ProducingAreaRequest;
import xin.marcher.module.construction.domain.request.QueryProducingAreaRequest;
import xin.marcher.module.construction.mapper.ProducingAreaMapper;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * 商品审核 资源管理
 */
@Repository
public class ProducingAreaRepository {

    @Resource
    private ProductConverter productConverter;

    @Resource
    private ProducingAreaMapper producingAreaMapper;


    public void saveOrUpdate(ProducingAreaRequest producingAreaRequest) {
        if (Objects.isNull(producingAreaRequest.getId())) {
            save(producingAreaRequest);
        } else {
            update(producingAreaRequest);
        }
    }


    private void save(ProducingAreaRequest producingAreaRequest) {
        ProducingAreaDO producingAreaDO = productConverter.converterDO(producingAreaRequest);
        producingAreaDO.initCommon();

        int count = producingAreaMapper.insert(producingAreaDO);
        if (count <= 0) {
            throw new ProductBizException(CommonErrorCodeEnum.SQL_ERROR);
        }
    }

    private void update(ProducingAreaRequest producingAreaRequest) {
        producingAreaMapper.updateById(productConverter.converterDO(producingAreaRequest));
    }


    public PageResult<ProducingAreaDTO> pageResult(QueryProducingAreaRequest queryProducingAreaRequest) {
        LambdaQueryWrapper<ProducingAreaDO> queryWrapper = Wrappers.lambdaQuery();
//        queryWrapper.like(ProducingAreaDO::getProducingAreaName, queryProducingAreaRequest.getProducingAreaNameLike());
        Page<ProducingAreaDO> page = new Page<>(queryProducingAreaRequest.getPageNum(), queryProducingAreaRequest.getPageSize());
        Page<ProducingAreaDO> producingAreaPage = producingAreaMapper.selectPage(page, queryWrapper);

        return productConverter.converterPageResult(producingAreaPage);
    }
}
